package com.wswy.wzcx.ui.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wswy.wzcx.ui.hold.ViewHolder;

import java.util.List;

/**
 * Created by wangduheng26 on 2018/1/5.
 * wangduheng26@gmail.com
 */

public abstract class BaseAdapter<T, V extends ViewHolder> extends RecyclerView.Adapter<V> {
    protected List<T> list;

    public BaseAdapter(List<T> list) {
        this.list = list;
    }

    @Override
    public V onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater from = LayoutInflater.from(parent.getContext());
        return onCreateViewHolder(from, parent, viewType);
    }


    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public T getItem(int position) {
        try {
            return list.get(position);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void onBindViewHolder(V holder, int position) {
        T item = getItem(position);
        holder.itemView.setTag(item);
        onBindViewHolder(holder, item, position);
        if(itemListener!=null){
            holder.itemView.setOnClickListener(itemListener);
        }
    }

    public abstract V onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType);

    public abstract void onBindViewHolder(V holder, T item, int position);

    protected View.OnClickListener itemListener;

    public void setItemOnClickListener(View.OnClickListener listener) {
        itemListener=listener;
    }
}
